package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private ICarPackageAuditService carPackageAuditService;

    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private RuntimeService runtimeService;
    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        //判断是否套餐,如果是套餐,需要吧审核状态设置初始化
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setSaleStatus(ServiceItem.AUDITSTATUS_INIT);
        }else {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);//设置默认的状态为无需审核
        }
        //设置默认的销售状态
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        ServiceItem oldObj = this.get(serviceItem.getId());
        //处于上架状态的商品不能修改
        if (ServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())) {
            throw new BusinessException("上架服务项目不能修改，请下架后再修改");
        }
        // 未上架,但是套餐处于审核状态,这时候也不能编辑
        if (ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage()) && ServiceItem.AUDITSTATUS_AUDITING.equals(oldObj.getAuditStatus())){
            throw new BusinessException("服务项目正在审核中,不可修改");
        }
        //如果是审核通过，此时修改，需要将其状态变更为初始化
        if (ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage()) && ServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else {
            //  原来是什么状态,也设置为什么状态
            serviceItem.setAuditStatus(oldObj.getAuditStatus());
        }
        //销售状态下架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void saleOn(Long id) {
        ServiceItem serviceItem = get(id);
        //如果不是套餐直接上架
        //如果是套餐,只有审核成功才能上架
        if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())
                && !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())){
            throw new BusinessException("套餐服务项需要审核通过之后才能上架");
        }
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    @Transactional
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        //根据传入的id查询服务项，服务项状态出于初始化才能进行审核逻辑
        ServiceItem serviceItem =  this.get(id);
        if(ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())
             || ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())
             || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())
             || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
             || ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus())
        ){
            throw new BusinessException("非法操作");
        }
        //审核信息记录
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(id);//服务单项Id
        audit.setServiceItemInfo(serviceItem.getInfo());//服务单项备注信息
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());//服务单项价格
        audit.setCreateTime(new Date());//创建时间
        audit.setCreator(ShiroUtils.getUser().getUserName());//创建人当前登录用户
        audit.setBpmnInfoId(bpmnInfoId);//流程定义ID
        audit.setInfo(info);//备注信息
        audit.setAuditorId(director);//审核人
        audit.setServiceItemName(serviceItem.getName());//服务单项名称
        //保存审核对象
        carPackageAuditService.save(audit);
        //启动流程实例，以金额作为实例参数
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        Map<String, Object> map = new HashMap<>();
        if(director != null){
            map.put("director", director.toString());
        }
        if(finance != null){
            map.put("finance", finance.toString());
        }
        map.put("discountPrice", serviceItem.getDiscountPrice().longValue());
        //启动流程
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceByKey(bpmnInfo.getActProcessKey(), audit.getId().toString(), map);
        //更新记录实例id
        audit.setInstanceId(processInstance.getId());
        carPackageAuditService.updateInstanceId(audit);
        //修改审核状态
        serviceItemMapper.changeAuditStatus(id,ServiceItem.AUDITSTATUS_AUDITING);
    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer auditStatusInit) {
        serviceItemMapper.changeAuditStatus(serviceItemId,auditStatusInit);
    }
}
